<?php
use think\db\Expression;
/**
 *  @file : common.php
 *  @brief: 模块公共函数
 */
/**
 *  @brief  : 更新订单/到账/返点
 *  @param [in] $PayChannel: 充值渠道, 1=支付宝; 2=汇付宝微信
 *  @param [in] $UserID    : 用户标识
 *  @param [in] $CardID    : [RYWebSMSDB].[dbo].[CardCoin]表主键
 *  @param [in] $ClientIP  : 客户端IP
 *  @param [in] $KindID    : 商品自定义分组标识; 0=大厅; 其他值表示特定游戏
 *  @param [in] $MerBillNo : 内部唯一订单号
 *  @param [in] $TradeNo   : 外部订单号
 *  @param [in] $Amount    : 实际订单金额
 *  @return : bool/RuntimeException
 *  @details: 在支付异步回调中调用
 */
function ChargeUpdate($PayChannel, $UserID, $CardID, $ClientIP, $KindID, $MerBillNo, $TradeNo, $Amount) {

  // 确定玩家
  $User = table('AccountsInfo', "rydb.basic")->where(['UserID' => $UserID])->find();
  if (empty($User)) {
    throw new RuntimeException("玩家[{$UserID}]不存在", 100);
  }


  // 确定商品
  $Goods = table('CardCoin', "rydb.websms")->where(['ID' => $CardID])->find();
  if (empty($Goods)) {
    throw new RuntimeException("商品[{$CardID}]不存在", 101);
  }
  
  // 金额判断
  if ($Goods['RMB'] * 1 != $Amount * 1) {
    throw new RuntimeException("实际金额[{$Amount}]与商品金额[{$Goods['RMB']}]不一致", 102);
  }
  
  // 订单处理
  $Charge = table('ChargeOnline', 'rydb.websms')->where(['UserID' => $User['UserID'], 'MerBillNo' => $MerBillNo])->find();
  if (empty($Charge)) { // 数据库中无该订单
    switch ($PayChannel) { //1=支付宝;2=汇付宝微信;
      case 1: $PayType = 'alipay'; break;
      case 2: $PayType = 'weixin'; break;
      default:$PayType = 'unknow'; break;
    }

    $eax = table('ChargeOnline', 'rydb.websms')->insertGetId([
      'UserID'    => $User['UserID'],
      'MerBillNo' => $MerBillNo,
      'RMB'       => $Goods['RMB'] * 1,
      'Addtime'   => new Expression('GETDATE()'),
      'Status'    => 1, // 1=支付成功; 0=未支付
      'PayType'   => $PayType,
      'wwwType'   => request()->server('SERVER_NAME/s', ''),
      'wwwIp'     => $ClientIP,
      'TradeNo'   => $TradeNo,
    ]);
    $Charge = table('ChargeOnline', 'rydb.websms')->where(['ID' => $eax])->find();
  }

  // 订单状态判断
  if ($Charge['GameStatus']) {
    throw new RuntimeException("订单[{$Charge['ID']}][{$Charge['MerBillNo']}]已到帐", 103);
  }

  $extra = 0; // 支付宝额外赠送
  if ($PayChannel == 1) { // 1=支付宝;2=汇付宝微信;
    switch ($User['Channel']) {
      case 43556: $extra = 20; break; // [43556]闲有娱乐
      case 43576: $extra = 20; break; // [43576]约战娱乐
      case 43583: $extra = 20; break; // [43583]UU娱乐
      case 43594: $extra = 20; break; // [43594]天天娱乐
      case 43598: $extra = 20; break; // [43598]同游娱乐
      case 43638: $extra = 20; break; // [43638]开心娱乐
    }
  }
  
  $URC = table('AccountsGameCurrency', 'rydb.basic')->where(['UserID' => $User['UserID']])->find();
  $SpreaderID   = empty($User['SpreaderID']) ? 0 : $User['SpreaderID'];
  $RoomCardOld  = empty($URC['RoomCard']) ? 0 : $URC['RoomCard'];
  $RoomCard = $Goods['Coin'] + ($SpreaderID > 0 ? $Goods['Zeng'] : 0) + $extra;  // 绑定代理额外赠送, 支付宝另外加送
  
  // 更新房卡数
  if (empty($URC)) {
    $eax = table('AccountsGameCurrency', 'rydb.basic')->insert([
      'UserID' => $User['UserID'], 'RoomCard' => $RoomCard,'ChargeNum'=>$Amount
    ]);
  } else {
    $eax = table('AccountsGameCurrency', 'rydb.basic')->where('ID', $URC['ID'])->setInc('RoomCard', $RoomCard);
    $eax2 = table('AccountsGameCurrency', 'rydb.basic')->where('ID', $URC['ID'])->setInc('ChargeNum', $Amount);
  }
  
  // 更新订单
  table('ChargeOnline', 'rydb.websms')->where('ID', $Charge['ID'])->update([
    'Status'      => 1,
    'GameStatus'  => 1,
    'Updatetime'  => new Expression('GETDATE()'),
  ]);
  
  $unit = '房卡';
  if ($User['Channel'] == 43592) {  // [43592]小月浙江游戏
    $unit = '钻石';
  }
  
  // 帐变记录
  $eax = $RoomCardOld + $RoomCard;
  $eax = table('CostRoomCardRecord', 'rydb.record')->insertGetId([
    'dwUserID'        => $User['UserID'],
    'dwCost'          => $RoomCard,
    'dwCostType'      => 10,  // 10=充值
    'beleftRoomCard'  => $eax,  // 变动后余额
    'describe'        => "充值{$Goods['RMB']}元，获得{$unit}{$RoomCard}张，剩余{$unit}{$eax}张",
    'CostTime'        => new Expression('GETDATE()'),
  ]);
/*
  $Goods['Type'] 商品分组标识
  1=公众号转账面额;
  2=公众号充值面额;
  3=支付宝充值面额;
  4=微信充值面额;
*/
  // 返点处理
  if ($Goods['Type'] != 2 && $SpreaderID > 0) {
    $toLevel = 0; // 表示几级返点
    $auid = $SpreaderID;
    $dtLevel = 0; // 直销比例, 用于上级计算
    do {  // 循环写入代理返点信息
      
      $Agent = table('AgentReg', 'rydb.websms')->where('UserID', $auid)->find();
      if (empty($Agent)) {
        throw new RuntimeException("代理[{$auid}]不存在", 104);
      }
      if ($Agent['Status'] == 0) {
        throw new RuntimeException("代理[{$auid}]未审核通过", 105);
      }
      if ($toLevel == 0) {
        $toLevel = $Agent['AgentLevel'];
      }

      if ($dtLevel > 0) {
        $myLevel = $dtLevel;
      } else {
        if ($Agent['AgentLevel'] >= 1 && $Agent['AgentLevel'] <= 7) {
          $eax = $toLevel - 1;
          $eax = "level{$eax}";
          $myLevel = $Agent[$eax];
        } else {
          $myLevel = 0;
        }
      }

      if ($myLevel == 0) {
        throw new RuntimeException("代理[{$auid}]未设置返点比率[{$myLevel}]", 106);
      }

      $myRebate = $Goods['RMB'] * $myLevel / 100; // 计算返点金额
      if ($myRebate <= 0) {
        throw new RuntimeException("代理[{$auid}]返点金额无效[{$myRebate}]", 107);
      }

      // 是否存在已返记录
      $eax = table('AgentChargeRebate', 'rydb.websms')->where([
        'AgentID' => $auid, 'MerBillNo' => $Charge['MerBillNo'], 'TradeNo' => $Charge['TradeNo'],
      ])->count();

      if ($eax == 0) { // 写入记录
        $eax = table('AgentChargeRebate', 'rydb.websms')->insert([
          'AgentID'     => $auid,
          'MerBillNo'   => $Charge['MerBillNo'],
          'TradeNo'     => $Charge['TradeNo'],
          'RMB'         => $Charge['RMB'],
          'myRebate'    => $myRebate,
          'myAgentLevel'=> $toLevel,  // 表示几级返点
          'myLevel'     => $myLevel,
          'Addtime'     => new Expression('GETDATE()'),
        ]);
      }
      if ($Agent['IsDirect']) {
        $dtLevel = $Agent['DirectLevel'];
      }
      if ($Agent['ParentId'] > 0) { // 代理还有上级代理
        $auid = $Agent['ParentId'];
      } else {
        break;
      }
    } while (true);
  }
  ////////////////////////////////////////////////////////////////////////////
  return true;
}
